package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

const TokenExpireDuration = time.Hour * 24

func (ml ml) Auth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.Request.Header.Get("token")
		if token == "" {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"msg": "请求未携带token，无权限访问",
			})
			ctx.Abort()
			return
		}
		verify, uid, err := ml.user.VerifyToken(token)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"msg": "服务器",
			})
			ctx.Abort()
			return
		}
		if !verify {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"msg": "鉴权失败",
			})
			ctx.Abort()
			return
		}
		// 将当前请求的uid信息保存到请求的上下文c上
		ctx.Set("uid", uid)
		ctx.Next() // 后续的处理函数可以用过c.Get("username")来获取当前请求的用户信息
	}
}
